package com.jmlee.component;

import com.jmlee.cache.AdminCache;
import com.jmlee.util.UUIDUtil;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.IOException;

/**
 * @Description 图形验证码生成工具类
 * @Author jmLee
 * @Date 2021/2/23 20:12
 * @Version 1.0
 */
@Component
public class CaptchaComp {

    @Autowired
    AdminCache adminCache;

    @Value("${server.servlet.context-path}")
    private String contextPath;

//    private static final String SESSION_KEY = "captcha";
    private static final int DEFAULT_LEN = 4;
    private static final int DEFAULT_WIDTH = 130;
    private static final int DEFAULT_HEIGHT = 48;


    private void setHeader(HttpServletResponse response) {
        response.setContentType("image/gif");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0L);
    }


    public void out(HttpServletResponse response) throws IOException {
        setHeader(response);

        // 生成一个随机数
        String captchaOwner = UUIDUtil.generateUUID();

        Cookie cookie = new Cookie("captchaOwner", captchaOwner);
        cookie.setMaxAge(100); // 100s过期
        cookie.setPath(contextPath);
        response.addCookie(cookie);

        // 三个参数分别为宽、高、位数
        SpecCaptcha specCaptcha = new SpecCaptcha(DEFAULT_WIDTH, DEFAULT_HEIGHT, DEFAULT_LEN);
        // 设置字体
        specCaptcha.setFont(new Font("Verdana", Font.PLAIN, 32));  // 有默认字体，可以不用设置
        // 设置类型，纯数字、纯字母、字母数字混合
        specCaptcha.setCharType(Captcha.TYPE_NUM_AND_UPPER);

        // 保存验证码到缓存中
        adminCache.setAuthCode(specCaptcha.text().toLowerCase(), captchaOwner, 100);

        specCaptcha.out(response.getOutputStream());
    }
}
